package cn.upfinder.allvideo.Activity;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.webkit.ValueCallback;
import android.webkit.WebView;
import android.webkit.WebViewClient;


import butterknife.BindView;
import butterknife.ButterKnife;
import cn.upfinder.allvideo.R;

public class HtmlActivity extends AppCompatActivity {

    @BindView(R.id.wvHtml)
    WebView wvHtml;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_html);
        ButterKnife.bind(this);
        wvHtml.getSettings().setJavaScriptEnabled(true);
        wvHtml.addJavascriptInterface(new MyJavaScriptInterface(this), "HtmlViewer");
        wvHtml.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                wvHtml.loadUrl("javascript:window.HtmlViewer.showHTML" +
                        "('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');");
            }
        });

        wvHtml.evaluateJavascript("(function() { return ('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>'); })();", new ValueCallback<String>() {
            @Override
            public void onReceiveValue(String s) {
                Log.d("HTML", s);
            }
        });
        wvHtml.loadUrl("http://www.baidu.com");
    }


    class MyJavaScriptInterface {

        private Context ctx;

        MyJavaScriptInterface(Context ctx) {
            this.ctx = ctx;
        }

        public void showHTML(String html) {
            Log.d("TAG", "showHTML: " + html);
            new AlertDialog.Builder(ctx).setTitle("HTML").setMessage(html)
                    .setPositiveButton(android.R.string.ok, null).setCancelable(false).create().show();
        }

    }
}
